<?php
/**
 * Created by PhpStorm.
 * Author: 芸签cms www.yunqiancms.com
 * User: sun
 * Date: 2022/7/5
 * Time: 1:21 PM
 */
namespace app\backend\modules\business\controllers;

use app\backend\controllers\BaseController;
use app\backend\modules\business\services\AdminUserService;
use app\backend\modules\sys\services\PermissionService;
use app\common\exceptions\BizException;
use app\common\exceptions\BizNoUnicodeException;
use app\common\models\AdminUser;
use app\common\models\DepartmentAdminUser;
use app\common\models\Permission;
use app\common\models\Role;
use app\common\models\UserProfile;
use app\common\helpers\Cache;
use app\common\models\UserRole;
use Illuminate\Support\Facades\Hash;
use Illuminate\Support\Facades\DB;
use Exception;


class StaffController extends BaseController
{
    public function index(){
        return view("backend.business.staff.index");
    }
    public function getList(){
        $search = request()->search;
        $list = (new AdminUserService())->getList($search);
        return $this->successJson('',$list);
    }

    /**
     * 获取当前登录用户基本信息
     * @return \Illuminate\Http\JsonResponse
     */
    public function getInfo()
    {
        //获取当前登录用户的账号
        $res = [];
        $res['uid'] = \YunCms::$adminUid;
        $res['username'] = \YunCms::$adminUserName;
        $userProfile = UserProfile::select()
            ->where('uid',$res['uid'])
            ->first();
        $res['mobile'] = $userProfile['mobile'];
        return $this->successJson("", $res);
    }
    /**
     * 修改用户登录密码
     */
    public function resetPassword()
    {
        $old_password = request()->old_password;
        $new_pass = request()->new_pass;
        $username = request()->username;

        $userModel = AdminUser::where('uid',\YunCms::$adminUid)->first();

        if (!$userModel){
            return $this->errorJson('用户不存在');
        }

        if (!Hash::check($old_password, $userModel->password))
        {
            return $this->errorJson('原密码错误');
        }
        $new_pass = bcrypt($new_pass);
        $data = [];
        $data['password'] = $new_pass;
        $res = AdminUser::where('uid', $userModel->uid)->update($data);
        return $this->successJson("修改成功");
    }
    public function detail(){
        return view("backend.business.staff.detail");
    }
    public function getDetail(){
        $id = intval(request()->id);
        $permissions = PermissionService::getPermission();
        $permissions = PermissionService::getApiData($permissions);
        $rolePermission = [];
        $rolePermissions = [];
        $user = [];
        $userPermissions = [];
        if($id){
            $userModel = AdminUser::select(['uid','username','status','created_at'])
                ->with(['userProfile' => function ($profile) {
                    return $profile->select()
                        ->with(['departmentAdminUsers' => function ($query) {
                            return $query->select()
                                ->with(['department' => function ($query) {
                                    return $query->select('id', 'name');
                                }]);
                        }]);
                }])
                ->with(['permissions' => function ($query) {
                    return $query->select();
                }])
                ->with(['userRole' => function ($role) {
                    return $role->select()
                        ->with(['role' => function ($role) {
                            return $role->select('id', 'name');
                        }]);
                }])
                ->where('uid',$id)
                ->first();
            if($userModel['uid']){
                $user = $userModel;
                $user['role_name'] = $userModel->userRole->role->name;
                $user['department_id'] = $userModel->userProfile->departmentAdminUsers[0]['department']['id'];
                $user['role_id'] = $userModel->userRole->role->id;
            }
            $roleModel = Role::getRoleById($user['role_id']);
            $rolePermission = $roleModel->toArray();
            $rolePermissions = [];
            foreach ($rolePermission['role_permission'] as $key=>$v) {
                $rolePermissions[] = $v['permission'];
            }
            foreach ($userModel['permissions'] as $v){
                $userPermissions[] = $v['permission'];
            }
            $userPermissions = array_merge($rolePermissions, $userPermissions);
        }
        $res = [
            'user'=>$user,
            'rolePermission'=>$rolePermissions,
            'permissions'=>$permissions,
            'userPermissions'=>$userPermissions
        ];
        return $this->successJson('',$res);
    }
    public function changeStatus()
    {
        $id = request()->id;
        $model = AdminUser::select()
            ->where('id',$id)
            ->first();
        if (empty($model)) {
            return $this->errorJson('未找到数据');
        }
        $status=AdminUser::STATUS_NORMAL;
        if($model->status==AdminUser::STATUS_NORMAL){
            $status= Role::STATUS_BAN;
        }
        $model->status = $status;
        $model->save();
        return $this->successJson();
    }
    public function create(){
        $userModel = new AdminUser();
        $requestUser = request()->user;
        $siteId = \YunCms::siteId();
        //dd($requestRole);
        if ($requestUser) {
            //将数据赋值到model
            $userModel->setRawAttributes($requestUser);
            //其他字段赋值
            $userModel->password = bcrypt($userModel->password);
            $userModel->type = AdminUser::TYPE_ADMIN;
            $userModel->remark = '';
            //字段检测
            $validator = $userModel->validator($userModel->getAttributes());
            //dd($validator->messages());
            if ($validator->fails()) {
                return  $this->errorJson("用户数据验证出错");
            }else{
                DB::beginTransaction();
                try {
                    $userModel->save();
                    $requestPermission = request()->permission;
                    $profile = request()->profile;
                    $params = request()->params;
                    $profileModel = new UserProfile();
                    $profile['uid'] = $userModel->uid;
                    $profileModel->setRawAttributes($profile);
                    $validator = $profileModel->validator();
                    if ($validator->fails()) {
                        DB::rollBack();
                        return $this->errorJson($validator->messages());
                    }
                    $profileModel->save();
                    $departmentAdminUserModel = new DepartmentAdminUser();
                    $departmentAdminUserModel->department_id = $params['department_id'];
                    $departmentAdminUserModel->uid = $userModel->uid;
                    $departmentAdminUserModel->save();
                    $userRoleModel = new UserRole();
                    $userRoleModel->user_id = $userModel->uid;
                    $userRoleModel->role_id = $params['role_id'];
                    $userRoleModel->save();
                    //数据处理
                    if ($requestPermission) {
                        //dd(1);
                        $data = [];
                        foreach ($requestPermission as $key => $value) {
                            $data[$key] = array(
                                'type'      => Permission::TYPE_USER,
                                'item_id'   => $userModel->uid,
                                'permission' => $value
                            );
                            $validator = (new Permission)->validator($data);
                            if ($validator->fails()) {
                                throw new BizException('角色数据验证出错');
                            }
                        }
                        \Log::debug('$requestPermission',$requestPermission);
                        $result = Permission::insert($data);
                        if (!$result) {
                            throw new BizException('角色数据验证出错');
                        }
                    }

                } catch (Exception $e) {
                    DB::rollBack();
                    return $this->errorJson($e->getMessage());
                }
                DB::commit();
                return $this->successJson('添加角色成功');
            }
        }else{
            return $this->errorJson("请传入用户信息");
        }
    }
    public function update(){
        $requestUser = request()->user;

        $id = $requestUser['uid'];
        $userModel = AdminUser::find($id);

        if ($requestUser) {
            $userModel->setRawAttributes($requestUser);
            $userModel->type = AdminUser::TYPE_ADMIN;
            $userModel->remark = '';
            $validator = $userModel->validator($userModel->getAttributes());
            if($requestUser['password']){
                $userModel->password = bcrypt($userModel->password);
            }
            if ($validator->fails()) {
                $this->errorJson('权限数据验证失败');
            } else {
                DB::beginTransaction();
                try {
                    $userModel->save();
                    $uid = $userModel->uid;
                    //return $this->message("更新角色成功");
                    Cache::flush();
                    $requestPermission = request()->permission;
                    $profile = request()->profile;
                    $params = request()->params;
                    $profileModel = UserProfile::getByUid($uid);
                    $profileModel->setRawAttributes($profile);
                    $validator = $profileModel->validator();
                    if ($validator->fails()) {
                        return $this->errorJson('用户附加数据验证出错');
                    }
                    $profileModel->save();
                    //这里只能做一对一，一对多要重新写
                    DepartmentAdminUser::where('uid',$uid)
                        ->update(['department_id'=>$params['department_id']]);
                    UserRole::where('user_id',$uid)
                        ->update(['role_id'=>$params['role_id']]);
                    if ($requestPermission) {
                        //dd(1);
                        $data = [];
                        foreach ($requestPermission as $key => $value) {
                            $data[$key] = array(
                                'type'      => Permission::TYPE_USER,
                                'item_id'   => $id,
                                'permission' => $value
                            );
                            $validator = (new Permission())->validator($data);
                            if ($validator->fails()) {
                                return $this->errorJson('权限数据验证失败');
                            }
                        }
                        //删除原权限数据，更新数据储存
                        Permission::deleteUserPermission($id);
                        $result = Permission::insert($data);
                        if (!$result) {
                            return $this->errorJson('角色更新成功，权限数据写入出错，请重新编辑权限！');
                        }
                    } else {
                        Permission::deleteRolePermission($id);
                    }
                } catch (Exception $e) {
                    DB::rollBack();
                    return $this->errorJson($e->getMessage());
                }
                DB::commit();
                return $this->successJson('编辑角色成功');
            }

        } else {
            return $this->errorJson("请传入用户信息");
        }
    }
    public function delete()
    {
        $id = request()->id;
        $requestRole = AdminUser::find($id);
        if (!$requestRole) {
            return $this->errorJson('未找到数据或已删除');
        }
        $resultRole = AdminUser::where('uid',$id)->delete();
        if ($resultRole) {
            $resultPermission = Permission::deleteUserPermission($id);
            UserProfile::where('uid',$id)->delete();
            if ($resultPermission) {
                return $this->successJson('删除角色成功。');
            }
            //是否需要怎么增加角色权限删除失败提示
        } else {
            return $this->errorJson('数据写入出错，请重试！');
        }
    }
}
